package com.example.qu_tao.View;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.R;
import com.example.qu_tao.adapter.PostAdapter;
import com.example.qu_tao.database.DBHelper;
import com.example.qu_tao.entity.Post;

import java.util.ArrayList;
import java.util.List;

public class WodeQutaoquanActivity extends AppCompatActivity {

    private ImageButton btnBack;
    private TextView tvTitle;
    private RecyclerView recyclerView;
    private PostAdapter postAdapter;
    private List<Post> postList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wodequtaoquan);

        initViews();
        setupRecyclerView();
        loadMyPosts();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        tvTitle = findViewById(R.id.tv_title);
        recyclerView = findViewById(R.id.recyclerView);

        btnBack.setOnClickListener(v -> finish());
        tvTitle.setText("我的趣淘圈");
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        postAdapter = new PostAdapter(this, postList);
        recyclerView.setAdapter(postAdapter);
    }

    @SuppressLint("Range")
    private void loadMyPosts() {
        new Thread(() -> {
            DBHelper dbHelper = new DBHelper(this);
            SQLiteDatabase db = dbHelper.getReadableDatabase();

            List<Post> loadedPosts = new ArrayList<>();

            // 查询当前用户的帖子（假设用户ID为1）
            String query = "SELECT posts.post_id, posts.user_id, user.user_name, posts.content, posts.post_type, posts.create_time " +
                    "FROM posts " +
                    "JOIN user ON posts.user_id = user._id " +
                    "WHERE posts.user_id = ? " +
                    "ORDER BY posts.create_time DESC";

            Cursor postCursor = db.rawQuery(query, new String[]{"1"});

            if (postCursor != null && postCursor.moveToFirst()) {
                do {
                    Post post = new Post();
                    post.setPostId(postCursor.getInt(postCursor.getColumnIndex("post_id")));
                    post.setUserId(postCursor.getInt(postCursor.getColumnIndex("user_id")));
                    post.setUsername(postCursor.getString(postCursor.getColumnIndex("user_name")));
                    post.setContent(postCursor.getString(postCursor.getColumnIndex("content")));
                    post.setPostType(postCursor.getInt(postCursor.getColumnIndex("post_type")));
                    post.setCreateTime(postCursor.getString(postCursor.getColumnIndex("create_time")));

                    // 查询关联的图片
                    List<byte[]> images = new ArrayList<>();
                    Cursor photoCursor = db.query("photo",
                            new String[]{"image"},
                            "post_id = ?",
                            new String[]{String.valueOf(post.getPostId())},
                            null, null, null);

                    if (photoCursor != null && photoCursor.moveToFirst()) {
                        do {
                            byte[] imageData = photoCursor.getBlob(photoCursor.getColumnIndex("image"));
                            if (imageData != null) { // 添加 null 检查
                                images.add(imageData);
                            }
                        } while (photoCursor.moveToNext());
                        photoCursor.close();
                    }

                    post.setImages(images);
                    loadedPosts.add(post);

                } while (postCursor.moveToNext());
                postCursor.close();
            }

            db.close();

            // 更新UI
            runOnUiThread(() -> {
                postList.clear();
                postList.addAll(loadedPosts);
                postAdapter.notifyDataSetChanged();
            });
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadMyPosts(); // 每次Activity可见时重新加载数据
    }
}